//
//  JJCommonTools.swift
//  JJAlbum
//
//  Created by 吴梓杭 on 2025/10/11.
//

import UIKit
import Photos
import CommonCrypto

let kProGateway = "http://192.168.0.112:8000"

let kHttpCodeSuccess = 200

//开发的时候打印，但是发布的时候不打印,使用方法，输入print(message: "输入")
public func print<T>(message: T, fileName: String = #file, methodName: String = #function, lineNumber: Int = #line) {
    /// 当前时间，精确到毫秒
    let dateNow = Date()
    let timeSinceArray = String(format: "%.6f", Double(dateNow.timeIntervalSince1970)).components(separatedBy: ".")  /// 避免在四舍五入时计算错误
    let data = Date.init(timeIntervalSince1970: Double(timeSinceArray[0]) ?? 0)
    let minuteFormatter = DateFormatter()
   minuteFormatter.dateFormat = "yyyy-MM-dd HH:mm"
    let secondFormatter = DateFormatter()
    secondFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    
    /// 当前print所在的文件名
    let lastName = ((fileName as NSString).pathComponents.last!)

    print("\(secondFormatter.string(from: data)).\(timeSinceArray[1]) [\(lastName)] [第\(lineNumber)行] \n\t\t \(message)")
}

func JJMainAsync(after: TimeInterval = 0, handler: @escaping (() -> Void)) {
    if after > 0 {
        DispatchQueue.main.asyncAfter(deadline: .now() + after) {
            handler()
        }
    } else {
        if Thread.isMainThread {
            handler()
        } else {
            DispatchQueue.main.async {
                handler()
            }
        }
    }
}


/// 给相册生成唯一标识符
func generateUniqueID(asset: PHAsset, completion: @escaping (String) -> Void) {
//   let size = asset.pixelWidth * asset.pixelHeight
   let creationDate = asset.creationDate?.timeIntervalSince1970 ?? 0
    let modificationDate = asset.modificationDate?.timeIntervalSince1970 ?? 0
    let mediaType = asset.mediaType.rawValue
    let mediaSubtypes = asset.mediaSubtypes.rawValue
    var fileName = "file_\(Int(creationDate))"
   
   if let resource = PHAssetResource.assetResources(for: asset).first {
       fileName = resource.originalFilename
   }
   
   let uniqueID = "\(fileName)-\(mediaType)-\(mediaSubtypes)-\(creationDate)-\(modificationDate)".md5
   completion(uniqueID)
}

class JJCommonTools: NSObject {
    
    // 根据最小公倍数计算出一个接近pageSize的值
    public var onceLoadCount: Int { Int(ceil(Double(1000) / Double(lcmColumns))) * lcmColumns }
    
    // 竖屏列数和横屏列数的最小公倍数
    public var lcmColumns = 12
    
    private var columnCounts = (portrait: 4, landscape: 6) {
        didSet {
            lcmColumns = lcm(columnCounts.portrait, columnCounts.landscape)
        }
    }
    
    private func gcd(_ a: Int, _ b: Int) -> Int {
        var a = a, b = b
        while b != 0 {
            (a, b) = (b, a % b)
        }
        return a
    }

    private func lcm(_ a: Int, _ b: Int) -> Int {
        return a * b / gcd(a, b)
    }
    
    class func formatVideoDuration(_ duration: TimeInterval) -> String {
        let duration = Int(round(duration))
        
        switch duration {
        case 0..<60:
            return String(format: "00:%02d", duration)
        case 60..<3600:
            let m = duration / 60
            let s = duration % 60
            return String(format: "%02d:%02d", m, s)
        case 3600...:
            let h = duration / 3600
            let m = (duration % 3600) / 60
            let s = duration % 60
            return String(format: "%02d:%02d:%02d", h, m, s)
        default:
            return ""
        }
    }
    
    
    // 检验相册状态
    class func authorizationPhotoLibraryStatus(_ completion: @escaping () -> Void) {
        let status = PHPhotoLibrary.authorizationStatus()
                switch status {
                case .authorized:
                    print("已授权访问相册")
                    // 可以访问相册
                    completion()
                case .denied, .restricted:
                    print("无相册访问权限")
                    // 引导用户去设置中开启权限
                    JJMainAsync(after: 0.5) {
                        if let topVC = QMUIHelper.visibleViewController {
                            let alertController = UIAlertController(title: "APP没有相册权限，需要您授权。", message: "", preferredStyle: .alert)
                            alertController.addAction(UIAlertAction(title: "开启权限", style: .default, handler: { _ in
                                guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
                                UIApplication.shared.open(url)
                            }))
                            alertController.addAction(UIAlertAction(title: "取消", style: .cancel))
                            topVC.present(alertController, animated: true, completion: nil)
                        }
                    }
                case .notDetermined:
                    print("尚未请求权限")
                    // 请求权限
                    PHPhotoLibrary.requestAuthorization { status in
                        JJMainAsync {
                            authorizationPhotoLibraryStatus(completion)
                        }
                    }
                case .limited:
                    print("有限访问权限")
                    // iOS 14+ 新增的有限访问模式
                    completion()
                @unknown default:
                    break
                }
    }
}

public extension PHAsset {
    var isInCloud: Bool {
        guard let resource = resource else {
            return false
        }
        return !(resource.value(forKey: "locallyAvailable") as? Bool ?? true)
    }

    var isGif: Bool {
        guard let filename = filename else {
            return false
        }
        
        return filename.hasSuffix("GIF")
    }
    
    var filename: String? {
        self.value(forKey: "filename") as? String
    }

    var resource: PHAssetResource? {
        PHAssetResource.assetResources(for: self).first
    }
    
}


// MD5扩展
extension Data {
    func md5() -> String {
        let length = Int(CC_MD5_DIGEST_LENGTH)
        var digest = [UInt8](repeating: 0, count: length)
        
        _ = self.withUnsafeBytes { body -> String in
            CC_MD5(body.baseAddress, CC_LONG(self.count), &digest)
            return ""
        }
        
        return (0..<length).reduce("") {
            $0 + String(format: "%02x", digest[$1])
        }
    }
}


extension String {
    var md5: String {
        let data = Data(self.utf8)
        return data.md5()
    }
}
